#include "guiterm.hpp"

Tab::Tab(Session *session, QWidget *parent)
	:QWidget(parent)
{
	this->session = session;
	this->window = NULL;
	
	setAutoFillBackground(true);
	setPalette(*PaletteManager::terminalWindow());
	
	scrollbar = new QScrollBar(this);
	scrollbar->setFocusPolicy(Qt::NoFocus);
	updateScrollbarPos();
	scrollbar->show();
	QObject::connect(scrollbar, SIGNAL(sliderMoved(int)), this, SLOT(scrollbarMoved(int)));
	
	this->contents = new TerminalFlow(scrollbar, this);
	contents->show();
}

Tab::~Tab()
{
	delete scrollbar;
	delete contents;
}

int Tab::getChildMaxHeight() const
{
	return childrenRect().height();
}

QScrollBar *Tab::getScrollbar()
{
	return scrollbar;
}

TerminalWindow *Tab::getWindow()
{
	return window;
}

void Tab::setWindow(TerminalWindow *window)
{
	this->window = window;
}

Session *Tab::getSession()
{
	return session;
}

string Tab::getName()
{
	return name;
}

string Tab::getLabel()
{
	return retprintf("%i %s", index, name.c_str());
}

void Tab::setName(string name)
{
	this->name = name;
	window->tabNameChanged(this);
}

int Tab::getIndex()
{
	return index;
}

void Tab::setIndex(int index)
{
	this->index = index;
	window->tabNameChanged(this);
}

void Tab::close()
{
	if(window)
		window->removeTab(this);
}

void Tab::appendSegment(ViewSegment *segment)
{
	contents->addSegment(segment);
	segment->show();
}

void Tab::removeSegment(ViewSegment *segment)
{
	contents->removeSegment(segment);
}

void Tab::resizeEvent(QResizeEvent *event)
{
	updateScrollbarPos();
	scrollbar->setPageStep(height());
	contents->setGeometry(0, 0, size().width()-scrollbarWidth, size().height());
}

void Tab::segmentHeightChanged(ViewSegment *segment, int newHeight)
{
	// TODO
}

void Tab::scrollbarMoved(int value)
{
	// TODO
}

void Tab::updateScrollbarPos()
{
	// Find out how wide the scrollbar wants to be
	QSize scrollbarSize = scrollbar->sizeHint();
	scrollbarWidth = scrollbarSize.width();
	
	// Place the scrollbar on the right side, full height
	QSize frameSize = size();
	scrollbar->setGeometry(frameSize.width()-scrollbarWidth, 0,
	                       scrollbarWidth, frameSize.height());
}

